#include <QUrl>
#include <QDebug>

#include "topicmanager.h"
#include "http/cvhttp.h"
#include "util/cvutil.h"
#include "cvsession.h"
#include "commentmanager.h"
TopicManager::TopicManager()
{
}

void TopicManager::getTopic(const QString &id)
{
    QUrl requestUrl = CVUtil::getBaseUrl("forum.get_forum_by_topic_id");
    requestUrl.addQueryItem("topic_guid", id);
    CVHttp *http = new CVHttp(requestUrl);
    //http->setDebug(true);
    connect(http, SIGNAL(finished(QScriptValue,QString)), this, SLOT(parseData(QScriptValue,QString)));
}

void TopicManager::getComments(const QString &id, int limit, int offset)
{
    CommentManager *commentMgr = new CommentManager();
    commentMgr->getTopicComments(id, limit, offset);
    connect(commentMgr, SIGNAL(handleComments(QList<Comment*>*)), this, SIGNAL(handleComments(QList<Comment*>*)));
}

void TopicManager::parseData(QScriptValue json, const QString &msg)
{

    if (!json.isError() && !json.isNull())
    {
        Topic *topic = new Topic();
        json = json.property("0");
        topic->setId(json.property("id").toString());
        topic->setTitle(json.property("title").toString());
        topic->setDescription(json.property("desc").toString());
        topic->setOwner(json.property("owner_id").toString());
        topic->setOwnerIcon(json.property("owner_icon").toString());
        topic->setTimeCreated(json.property("time_created").toString());
        emit handleTopic(topic, "");
    }
    else
    {
        emit handleTopic(0, msg);
    }
}
